package net.pws.oos.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.pws.common.beanutils.BeanUtils;
import net.pws.common.util.StringUtils;
import net.pws.common.jackson.JsonUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.oos.biz.model.Area;
import net.pws.oos.biz.model.Dict;
import net.pws.oos.biz.model.Organization;
import net.pws.oos.biz.model.Project;
import net.pws.oos.biz.query.DictFinder;
import net.pws.oos.biz.query.ProjectFinder;
import net.pws.oos.biz.query.SystemManageFinder;
import net.pws.oos.biz.query.parameter.ProjectQueryParameter;
import net.pws.oos.biz.service.ProjectService;
import net.pws.oos.security.SecurityUtils;
import net.pws.oos.web.dto.ProjectDto;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/biz/project")
@SuppressWarnings("rawtypes")
public class ProjectAction {
    
    private final transient Log logger = LogFactory.getLog(ProjectAction.class);
    
    @Autowired
    private EntityManager entityManager;
    
    @Autowired
    private ProjectService projectService;
    
    @Autowired
    private ProjectFinder projectFinder;
    
    @Autowired
    private SystemManageFinder systemManageFinder;
    
    @Autowired
    private DictFinder dictFinder;
    
    @RequestMapping("/count.json")
    @ResponseBody
    public Object getProjectCount(ProjectQueryParameter queryParams) {
        try {
            queryParams = initQueryParams(queryParams);
            return JsonUtils.succeedMap(projectFinder.count(queryParams));
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/list.json")
    @ResponseBody
    public Object getProjectList(ProjectQueryParameter queryParams) {
        try {
            queryParams = initQueryParams(queryParams);
            List<Map> projects = projectFinder.getProjectList(queryParams,
                                                              queryParams.getStart(),
                                                              queryParams.getLimit());
            return JsonUtils.succeedMap(projects);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/excel.do")
    public String exportExcel(ProjectQueryParameter queryParams, ModelMap map) {
        queryParams = initQueryParams(queryParams);
        queryParams = initQueryParams(queryParams);
        List<Map> list = projectFinder.getProjectList(queryParams,
                                                      0,
                                                      Integer.MAX_VALUE);
        map.put("list", list);
        return "project/excel";
    }
    
    private ProjectQueryParameter initQueryParams(ProjectQueryParameter queryParams) {
        if (queryParams == null) {
            queryParams = new ProjectQueryParameter();
        }
        
        if (StringUtils.isBlank(queryParams.getOrganId())) {
            Organization organ = findCurrentCompany();
            if (organ != null) {
                queryParams.setOrganId(organ.getId());
            }
        }
        return queryParams;
    }
    
    // 得到分公司
    private Organization findCurrentCompany() {
        String organId = SecurityUtils.currentUser().getOrganId();
        return systemManageFinder.getDepthOrganization(organId, 1);
    }
    
    // 得到分公司列表
    private List<Organization> findOwnerCompanies() {
        Organization organ = findCurrentCompany();
        if (organ != null) {
            List<Organization> list = new ArrayList<Organization>();
            list.add(organ);
            return list;
        }
        
        List<Organization> tops = systemManageFinder.getOrganizationChildren(null);
        return systemManageFinder.getOrganizationChildren(tops.get(0).getId());
    }
    
    @RequestMapping("/list.do")
    public String listPage(ModelMap map) {
        map.put("organs", findOwnerCompanies());
        map.put("customers", dictFinder.listDicts(Dict.CUSTOMER));
        map.put("specials", dictFinder.listDicts(Dict.SPECIAL));
        return "project/list";
    }
    
    @RequestMapping("/edit.do")
    public String editPage(String id, ModelMap map) {
        map.put("organs", findOwnerCompanies());
        map.put("customers", dictFinder.listDicts(Dict.CUSTOMER));
        map.put("specials", dictFinder.listDicts(Dict.SPECIAL));
        
        return "project/edit";
    }
    
    @RequestMapping("/query.do")
    public String queryPage(ModelMap map) {
        map.put("customers", dictFinder.listDicts(Dict.CUSTOMER));
        map.put("specials", dictFinder.listDicts(Dict.SPECIAL));
        
        return "project/query";
    }
    
    @RequestMapping("/detail.json")
    @ResponseBody
    public Object detail(String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonUtils.failedMap("错误的参数！");
        }
        
        Map project = projectFinder.getProject(id);
        if (project == null) {
            return JsonUtils.failedMap("您查找到项目不存在！");
        }
        
        return JsonUtils.succeedMap(project);
    }
    
    @RequestMapping("/save.json")
    @ResponseBody
    public Object save(ProjectDto dto) {
        // 判断是否重名
        // if (projectFinder.isProjectExists(dto.getName(),
        // dto.getCode(),
        // dto.getId())) {
        // return JsonUtils.failedMap("项目名或编码已存在！");
        // }
        
        try {
            Project project = null;
            if (StringUtils.isNotEmpty(dto.getId())) {
                project = entityManager.find(Project.class, dto.getId());
            }
            if (project == null) {
                project = new Project();
            }
            
            String[] ignoredProps = { "id",
                                     "organ",
                                     "area",
                                     "special",
                                     "customer" };
            BeanUtils.copyProperties(project, dto, ignoredProps);
            if (StringUtils.isNotBlank(dto.getOrganId())) {
                project.setOrgan(entityManager.getReference(Organization.class,
                                                            dto.getOrganId()));
            }
            if (StringUtils.isNotBlank(dto.getAreaId())) {
                project.setArea(entityManager.getReference(Area.class,
                                                           dto.getAreaId()));
            }
            if (StringUtils.isNotBlank(dto.getSpecialId())) {
                project.setSpecial(entityManager.getReference(Dict.class,
                                                              dto.getSpecialId()));
            }
            if (StringUtils.isNotBlank(dto.getCustomerId())) {
                project.setCustomer(entityManager.getReference(Dict.class,
                                                               dto.getCustomerId()));
            }
            
            projectService.save(project);
            return JsonUtils.succeedMap(project.getId());
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/delete.json")
    @ResponseBody
    public Object delete(String id) {
        return null;
    }
}
